from django.contrib.auth import get_user_model
from django.conf import settings

from rest_framework.decorators import api_view
from rest_framework.response import Response
import redis

from ..serializers import PublicProfileSerializer
from ..models import Profile

User = get_user_model()



@api_view(['GET', 'POST'])
def profile_detail_api_view(request, username, *args, **kwargs):
    qs = Profile.objects.filter(user__username=username)
    if not qs.exists():
        return Response({"detail": "User not found"}, status=404)
    profile_obj = qs.first()
    data = request.data or {}
    if request.method == "POST":
        me = request.user
        action = data.get("action")
        if profile_obj.user != me:
            if action == "follow":
                profile_obj.followers.add(me)
            elif action == "unfollow":
                profile_obj.followers.remove(me)
            else:
                pass
    r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)
    redis_key = 'profile:{}:views'.format(username)
    if r.get(redis_key) is None:
        r.set(redis_key, 1)
        total_views = 1
    else:
        if request.method == 'GET':
            total_views = r.incr(redis_key)
        else:
            total_views = r.get(redis_key)
    serializer = PublicProfileSerializer(
        instance=profile_obj, context={"request": request, "total_views": total_views})
    return Response(serializer.data, status=200)
